const dayjs = require('dayjs');
// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { cloudHelper, pageHelper, timeHelper, dataHelper, ProjectBiz, PassportBiz, FlowBiz } = pathImport;
const projectSetting = require('../../../../../config/projects_config.js');

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);

		console.log('修改申请页面参数:', options);

		// 缓存原始参数，用于重新加载
		this._options = options;

		// 初始化数据
		this.setData({
			isLoad: false,
			id: null,
			cateId: null,
			flow: null,
			fields: null
		});

		// 添加页面超时保护
		setTimeout(() => {
			if (this.data.isLoad === false) {
				console.error('页面加载超时，强制设置isLoad=true');
				this.setData({
					isLoad: true
				});
			}
		}, 8000);

		// 参数校验和处理
		try {
			// 处理ID参数
			let id = options.id;
			if (id) {
				// 如果ID是对象格式，提取_id
				if (typeof id === 'object' && id._id) {
					id = id._id;
				}
				// 移除可能存在的空格
				id = id.trim();
				this.setData({ id });
				console.log('处理后的ID:', id);
			}

			// 如果没有ID，尝试从本地存储获取
			if (!id) {
				let lastFlowData = wx.getStorageSync('last_flow_data');
				if (lastFlowData && lastFlowData.id) {
					let now = dayjs().valueOf();
					if ((now - lastFlowData.time) < 30 * 60 * 1000) { // 30分钟内有效
						id = lastFlowData.id;
						this.setData({ id });
						console.log('使用本地存储的ID:', id);
					} else {
						console.log('本地存储的ID已过期');
						wx.removeStorageSync('last_flow_data');
					}
				}
			}

			// 登录检查
			if (!await PassportBiz.loginMustBackWin(this)) {
				return;
			}

			// 加载流程详情
			if (id) {
				console.log('开始加载流程详情');
				let flow = await cloudHelper.callCloudData('flow/view', { id });
				
				if (!flow) {
					throw new Error('未找到流程数据');
				}

				// 设置分类ID
				let cateId = flow.FLOW_CATE_ID;
				if (!cateId) {
					console.warn('流程数据缺少分类ID，尝试备选方案');
					// 尝试通过名称匹配获取分类ID
					if (flow.FLOW_CATE_NAME) {
						let allSteps = projectSetting.FLOW_ALL_STEPS;
						for (let k = 0; k < allSteps.length; k++) {
							if (allSteps[k].FLOW_NAME == flow.FLOW_CATE_NAME) {
								cateId = allSteps[k].FLOW_CATE_ID;
								flow.FLOW_CATE_ID = cateId; // 补充缺失的分类ID
								console.log('通过名称匹配补充了分类ID:', cateId);
								break;
							}
						}
					}
					
					// 如果仍然没有找到，使用默认的第一个分类
					if (!cateId && projectSetting.FLOW_ALL_STEPS.length > 0) {
						cateId = projectSetting.FLOW_ALL_STEPS[0].FLOW_CATE_ID;
						flow.FLOW_CATE_ID = cateId;
						console.log('使用默认分类ID:', cateId);
					}
					
					// 如果所有尝试都失败了，才抛出错误
					if (!cateId) {
						throw new Error('未找到分类ID');
					}
				}

				this.setData({
					flow,
					cateId
				});

				console.log('加载到流程数据:', flow);

				// 查找对应的步骤
				let allSteps = projectSetting.FLOW_ALL_STEPS;
				let curStep = null;
				
				// 通过FLOW_CATE_ID匹配
				for (let k = 0; k < allSteps.length; k++) {
					if (allSteps[k].FLOW_CATE_ID == cateId) {
						curStep = allSteps[k];
						console.log('匹配到步骤:', curStep.FLOW_NAME);
						break;
					}
				}

				// 如果没找到，尝试通过名称匹配
				if (!curStep && flow.FLOW_CATE_NAME) {
					for (let k = 0; k < allSteps.length; k++) {
						if (allSteps[k].FLOW_NAME == flow.FLOW_CATE_NAME) {
							curStep = allSteps[k];
							console.log('通过名称匹配到步骤:', curStep.FLOW_NAME);
							break;
						}
					}
				}

				if (curStep) {
					this.setData({
						curStep,
						title: curStep.FLOW_NAME
					});

					// 设置导航栏标题
					wx.setNavigationBarTitle({
						title: '申请单修改 - ' + curStep.FLOW_NAME
					});

					// 获取表单字段
					let fields = curStep.FLOW_FIELDS;
					if (!fields && flow.FLOW_FORMS) {
						// 从现有表单反向构建字段
						fields = [];
						let forms = flow.FLOW_FORMS;
						for (let i = 0; i < forms.length; i++) {
							fields.push({
								mark: forms[i].mark,
								title: forms[i].title,
								type: forms[i].type,
								must: false
							});
						}
						console.log('从表单构建出字段:', fields.length);
					}

					this.setData({ fields });
				} else {
					throw new Error('未找到匹配的流程步骤');
				}
			} else {
				throw new Error('未提供流程ID');
			}

			this.setData({ isLoad: true });

		} catch (err) {
			console.error('加载流程详情失败:', err);
			
			// 显示错误提示
			wx.showToast({
				title: err.message || '加载失败，请重试',
				icon: 'none',
				duration: 2000
			});

			// 确保设置加载完成状态
			this.setData({
				isLoad: true,
				flow: null,
				fields: null
			});
		}
	},

	_loadDetail: async function () {
		if (!this.data.id) {
			console.error('没有提供流程ID');
			wx.showToast({
				title: '未找到流程数据',
				icon: 'none',
				duration: 2000
			});
			this.setData({
				isLoad: true, // 确保在ID为空时也设置isLoad为true
				flow: null  // 明确设置为null，这样模板可以显示错误提示
			});
			return;
		}
		
		try {
			console.log('开始加载流程详情，ID:', this.data.id);
			await FlowBiz.loadDetail(this);
			console.log('流程详情加载结果:', this.data.flow ? '成功' : '失败');
			
			if (!this.data.flow) {
				console.error('未找到流程数据');
				wx.showToast({
					title: '未找到流程数据',
					icon: 'none',
					duration: 2000
				});
				this.setData({
					isLoad: true, // 确保在未找到流程时也设置isLoad为true
					flow: null  // 明确设置为null，这样模板可以显示错误提示
				});
				return;
			}
			
			console.log('流程数据:', this.data.flow);
			
			// 如果curStep为空，重新尝试获取
			if (!this.data.curStep) {
				console.log('重新尝试匹配流程步骤');
				let flow = this.data.flow;
				let allSteps = projectSetting.FLOW_ALL_STEPS;
				
				let curStep = null;
				// 尝试通过FLOW_CATE_ID匹配
				for (let k = 0; k < allSteps.length; k++) {
					if (allSteps[k].FLOW_CATE_ID == flow.FLOW_CATE_ID) {
						curStep = allSteps[k];
						console.log('通过CATE_ID匹配到步骤:', curStep.FLOW_NAME);
						break;
					}
				}
				
				// 如果没找到，尝试通过FLOW_CATE_NAME匹配
				if (!curStep && flow.FLOW_CATE_NAME) {
					for (let k = 0; k < allSteps.length; k++) {
						if (allSteps[k].FLOW_NAME == flow.FLOW_CATE_NAME) {
							curStep = allSteps[k];
							console.log('通过CATE_NAME匹配到步骤:', curStep.FLOW_NAME);
							break;
						}
					}
				}
				
				// 如果还是没找到，使用第一个
				if (!curStep && allSteps.length > 0) {
					curStep = allSteps[0];
					console.log('未找到匹配步骤，使用默认步骤:', curStep.FLOW_NAME);
				}
				
				if (curStep) {
					this.setData({
						curStep,
						title: curStep.FLOW_NAME,
						cateId: curStep.FLOW_CATE_ID
					});
				} else {
					console.error('无法获取有效的流程步骤');
				}
			}
			
			// 更新数据 - 即使没有curStep也尝试直接从flow中获取表单字段
			let fields = null;
			if (this.data.curStep && this.data.curStep.FLOW_FIELDS) {
				fields = this.data.curStep.FLOW_FIELDS;
				console.log('从curStep获取到fields:', fields.length);
			} else if (this.data.flow.FLOW_FORMS) {
				// 尝试从flow中反向构建fields
				console.log('尝试从flow表单反向构建fields');
				fields = [];
				let forms = this.data.flow.FLOW_FORMS;
				for (let i = 0; i < forms.length; i++) {
					let form = forms[i];
					fields.push({
						mark: form.mark,
						title: form.title,
						type: form.type,
						must: false
					});
				}
				console.log('从flow表单构建出fields:', fields.length);
			}
			
			this.setData({
				fields,
				isLoad: true // 确保设置isLoad为true
			});
			
		} catch (err) {
			console.error('加载流程详情失败:', err);
			wx.showToast({
				title: '加载流程数据失败',
				icon: 'none',
				duration: 2000
			});
			this.setData({
				isLoad: true, // 确保即使出错也设置isLoad为true
				flow: null,   // 明确设置为null，这样模板可以显示错误提示
				fields: null  // 明确设置为null，这样模板可以显示错误提示
			});
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () { },

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {
		this.setData({
			isLoad: false
		}, async () => {
			await this._loadDetail();
		});
		wx.stopPullDownRefresh();
	},

	url: function (e) {
		pageHelper.url(e, this);
	},

	bindCheckTap: async function (e) {
		if (!this.data.flow || !this.data.fields) {
			wx.showToast({
				title: '表单数据不完整',
				icon: 'none'
			});
			return;
		}
		
		try {
			this.selectComponent("#flow-form-show").checkForms();
		} catch (err) {
			console.error('表单检查失败:', err);
			wx.showToast({
				title: '表单组件异常',
				icon: 'none'
			});
		}
	},

	bindSubmitCmpt: async function (e) {
		let forms = e.detail;
		let callback = async () => {
			try {
				let id = this.data.id;
				let params = {
					id,
					forms
				}
				await cloudHelper.callCloudSumbit('flow/edit', params);

				await cloudHelper.transFormsTempPics(forms, 'flow-day/' + timeHelper.time('Y-M-D') + '/', id, 'flow/update_forms', { step: 1 });

				let cb = () => {
					let node = {
						'FLOW1_OBJ': {
							'person': dataHelper.getDataByKey(forms, 'mark', 'person').val,
							'phone': dataHelper.getDataByKey(forms, 'mark', 'phone').val
						}
					}
					pageHelper.modifyPrevPageListNodeObject(id, node);

					wx.navigateBack();
				};
				pageHelper.showModal('已提交，请耐心等待审批', '温馨提示', cb);
			} catch (err) {
				console.log(err);
			}
		}

		wx.requestSubscribeMessage({
			tmplIds: [projectSetting.NOTICE_TEMP_RESULT_FLOW, projectSetting.NOTICE_TEMP_NEW_FLOW],
			async complete() {
				callback();
			}
		});
	},

	bindBackTap: function () {
		wx.navigateBack();
	},
	
	bindReloadTap: async function() {
		try {
			wx.showLoading({
				title: '重新加载中',
				mask: true
			});
			
			console.log('重新加载申请表单，当前ID:', this.data.id);
			
			// 先重置加载状态
			this.setData({ 
				isLoad: false,
				flow: null,
				fields: null
			});
			
			// 加载表单详情
			await this._loadDetail();
			
			wx.hideLoading();
		} catch(err) {
			console.error('重新加载失败:', err);
			wx.hideLoading();
			wx.showToast({
				title: '重新加载失败',
				icon: 'none'
			});
			this.setData({ isLoad: true });
		}
	},
})